package com.alibaba.citrus.ots.platform.enhance.repository.impl;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.platform.enhance.repository.OperateLogWriteRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crplatformenhance.domain.operatelog.dto.CreateOperateLogResponse;
import com.epoch.app.crplatformenhance.domain.operatelog.model.OperateLog;
import com.epoch.app.crplatformenhance.domain.operatelog.service.OperateLogService;
import com.epoch.app.crplatformenhance.model.dto.BatchSaveOperateLogRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author: qiaojiange
 * @create: 2021/11/10
 * @Description 操作日志资源层实现
 */
@Repository
public class OperateLogWriteRepositoryImpl implements OperateLogWriteRepository {

    private Log log = Log.getLogger(OperateLogWriteRepositoryImpl.class);

    @Resource
    private OperateLogService operateLogService;

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean write(OperateLog operateLog) {
        if(Objects.isNull(operateLog)){
            return false;
        }
        CreateOperateLogResponse response = operateLogService.createOperateLog(operateLog);
        return response != null ? StringUtils.isNotBlank(response.getLastInsertId()) : false;
    }

    /**
     * 保存操作日志
     *
     * @param operateLogList 操作日志
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean batchSaveOperateLog(List<OperateLog> operateLogList) {
        if (CollectionUtils.isEmpty(operateLogList)) {
            return true;
        }
        BatchSaveOperateLogRequest request = new BatchSaveOperateLogRequest();
        request.setOperateLogList(operateLogList);
        //oldValue和NewValue不存储
        operateLogList.forEach(operateLog -> {
            operateLog.setOldValue(null);
            operateLog.setNewValue(null);;
        });
        Result<Void> result = operateLogService.batchSaveOperateLog(request);
        if (Objects.nonNull(result) && result.isSuccess()) {
            return true;
        } else {
            log.error("批量保存失败!");
            return false;
        }
    }


}
